package com.usian.user.filter;

import com.usian.common.threadlocal.UserThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Order(1)
@WebFilter(filterName = "userFilter",urlPatterns = "/api/*")
public class UserFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取请求头中用户id
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        String userId = httpServletRequest.getHeader("userId");
        //判断用户id是否存在，并且是否为0
        if(StringUtils.isNotBlank(userId) && Integer.valueOf(userId).intValue() != 0){
            UserThreadLocalUtils.setUserId(Integer.parseInt(userId));
        }
        //放行过滤器请求
        chain.doFilter(request, response);
    }
}
